package com.cn.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.model.system.SysDept;
import com.cn.system.mapper.SysDeptMapper;
import com.cn.system.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    //部门列表
    @Override
    public List<SysDept> findNodes() {
        List<SysDept> sysDepts=this.list();
        if (CollectionUtils.isEmpty(sysDepts)) return null;
        List<SysDept> result = buildTree(sysDepts);
        //
        return result;
    }

    public static List<SysDept> buildTree(List<SysDept> sysDepts) {
        List<SysDept> trees = new ArrayList<>();
        for (SysDept SysDept : sysDepts) {
            if (SysDept.getParentId().longValue() == 0) {
                trees.add(findChildren(SysDept,sysDepts));
            }
        }
        return trees;
    }

    private static SysDept findChildren(SysDept SysDept, List<SysDept> treeNodes) {
        SysDept.setChildren(new ArrayList<SysDept>());
        for (SysDept it : treeNodes) {
            if (Long.parseLong(SysDept.getId())==it.getParentId()){
                if (SysDept.getChildren()==null){
                    SysDept.setChildren(new ArrayList<>());
                }
                SysDept.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return SysDept;
    }
}
